import json

from django.shortcuts import render

# Create your views here.
import random

from django.http import HttpResponse, JsonResponse
from django.shortcuts import render
from dwebsocket.decorators import accept_websocket # 引入dwbsocket的accept_websocket装饰器
# Create your views here.

clients={} #创建客户端列表，存储所有在线客户端

def sendmsg(request):
    return render(request,'chat/chat.html')


def recvmsg(request):
    return render(request,'chat/recvmsg.html')

def getuser(request):
    str_ = request.body.decode()
    dict_ = json.loads(str_)
    username = dict_['username']
    print(username)
    if username in clients:
        result = {'code':200}
        return JsonResponse(result)
    else:
        result = {'code':10100,'error':'用户不存在'}
        return JsonResponse(result)



# 允许接受ws请求
@accept_websocket
def link(request):
    print('link函数')
    # 判断是不是ws请求
    # uuid = random.randint(0,100)
    print(request.is_websocket())
    if request.is_websocket():

        # 判断是否有客户端发来消息，若有则进行处理，若发来“test”表示客户端与服务器建立链接成功
        while True:
            print('等待..')
            message=request.websocket.wait()
            print('等待完成')
            if not message:
                print('exit')
                break
            else:
                msg_list = message.decode().split(':')
                print("客户端链接成功："+str(message, encoding = "utf-8"))
                #保存客户端的ws对象，以便给客户端发送消息,每个客户端分配一个唯一标识
                print(msg_list)
                clients[msg_list[1]]=request.websocket
                print(msg_list[1])
                print(clients)


def send(request):
    print('send函数')
    # 获取消息
    msg=request.POST.get("msg")
    print(msg)
    msg_list = msg.split(':')
    user = msg_list[1]
    target_user = msg_list[0]
    info = msg_list[2]
    # 获取到当前所有在线客户端，即clients
    # 遍历给所有客户端推送消息
    # for client in clients:
    #     clients[client].send(msg.encode('utf-8'))
    #     print(client)
    clients[user].send(target_user+':'+info)
    return HttpResponse({"msg":"success"})